package bbs.controller;

import bbs.annotation.GlobalInterceptor;
import bbs.annotation.VerifyParam;
import bbs.controller.base.ABaseController;
import bbs.entity.config.AdminConfig;
import bbs.entity.config.WebConfig;
import bbs.entity.constants.Constants;
import bbs.entity.dto.SessionWebUserDto;
import bbs.entity.enums.*;
import bbs.entity.po.*;
import bbs.entity.query.ForumArticleAttachmentQuery;
import bbs.entity.query.ForumArticleQuery;
import bbs.entity.query.ForumCommentQuery;
import bbs.entity.vo.PaginationResultVO;
import bbs.entity.vo.ResponseVO;
import bbs.entity.vo.web.FormArticleDetailVO;
import bbs.entity.vo.web.FormArticleUpdateDetailVO;
import bbs.entity.vo.web.ForumArticleAttachmentVo;
import bbs.entity.vo.web.ForumArticleVO;
import bbs.exception.BusinessException;
import bbs.service.*;
import bbs.utils.CopyTools;
import bbs.utils.StringTools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;


@RestController("forumArticleController")
@RequestMapping({"/forum"})
public class ForumArticleController extends ABaseController {
    private static final Logger logger = LoggerFactory.getLogger(ForumArticleController.class);

    @Resource
    private WebConfig webConfig;

    @Resource
    private ForumBoardService forumBoardService;

    @Resource
    private ForumArticleService forumArticleService;

    @Resource
    private ForumArticleAttachmentService forumArticleAttachmentService;

    @Resource
    private ForumCommentService forumCommentService;

    @Resource
    private ForumArticleAttachmentDownloadService forumArticleAttachmentDownloadService;

    @Resource
    private LikeRecordService likeRecordService;

    @Resource
    private UserInfoService userInfoService;

    @Resource
    private AdminConfig adminConfig;


    @RequestMapping("/loadArticle")
    public ResponseVO loadArticle(ForumArticleQuery articleQuery) {
        articleQuery.setOrderBy("post_time desc");
        return getSuccessResponseVO(forumArticleService.findListByPage(articleQuery));
    }

    @RequestMapping("/delArticle")
    public ResponseVO delArticle(@VerifyParam(required = true) String articleIds) {
        forumArticleService.delArticle(articleIds);
        return getSuccessResponseVO(null);
    }

    @RequestMapping("/updateBoard")
    public ResponseVO uploadArticle(@VerifyParam(required = true) String articleId, Integer pBoardId, Integer boardId) {
        boardId = boardId == null ? 0 : boardId;
        forumArticleService.UpdateBoard(articleId,pBoardId,boardId);
        return getSuccessResponseVO(null);
    }

    @RequestMapping("/getAttachment")
    public ResponseVO getAttachment(@VerifyParam(required = true) String articleId) {
        ForumArticleAttachmentQuery articleAttachmentQuery = new ForumArticleAttachmentQuery();
        articleAttachmentQuery.setArticleId(articleId);
        List<ForumArticleAttachment> articleAttachmentList = forumArticleAttachmentService.findListByParam(articleAttachmentQuery);

        if  (articleAttachmentList.isEmpty()) throw new BusinessException(Constants.ATTACHMENT_NOT_EXISTS);

        return getSuccessResponseVO(articleAttachmentList.get(0));
    }

    /**
     * 附件下载
     * @param request
     * @param response
     * @param fileId
     */
    @RequestMapping({"/attachmentDownload"})
    @GlobalInterceptor(checkLogin = true, checkParams = true)
    public void attachmentDownload(HttpServletRequest request, HttpServletResponse response, @VerifyParam(required = true) String fileId)
    {
        ForumArticleAttachment forumArticleAttachment = this.forumArticleAttachmentService.getForumArticleAttachmentByFileId(fileId);
        FileInputStream fileInputStream = null;
        ServletOutputStream servletOutputStream = null;
        String downloadFileName = forumArticleAttachment.getFileName();
        String filePath = adminConfig.getProjectFolder() + "/file/" + "attachment/" + forumArticleAttachment.getFilePath();
        File file = new File(filePath);
        try {
            fileInputStream = new FileInputStream(file);
            servletOutputStream = response.getOutputStream();
            response.setContentType("application/x-msdownload; charset=UTF-8");
            if (request.getHeader("User-Agent").toLowerCase().indexOf("msie") > 0) {
                downloadFileName = URLEncoder.encode(downloadFileName, "UTF-8");
            } else {
                downloadFileName = new String(downloadFileName.getBytes("UTF-8"), "ISO8859-1");
            }
            response.setHeader("Content-Disposition", "attachment;filename=\"" + downloadFileName + "\"");
            byte[] arrayOfByte = new byte[1024];
            int len = 0;
            while ((len = fileInputStream.read(arrayOfByte)) != -1)
                servletOutputStream.write(arrayOfByte, 0, len);
            servletOutputStream.flush();
        } catch (Exception exception) {
            logger.error("下载异常", exception);
            throw new BusinessException("下载失败");
        } finally {
            try {
                if (fileInputStream != null)
                    fileInputStream.close();
            } catch (IOException iOException) {
                logger.error("IO异常", iOException);
            }
            try {
                if (servletOutputStream != null)
                    servletOutputStream.close();
            } catch (IOException iOException) {
                logger.error("IO异常", iOException);
            }
        }
    }

    @RequestMapping("/topArticle")
    public ResponseVO topArticle(@VerifyParam(required = true) String articleIds, Integer topType) {
        ForumArticle forumArticle = new ForumArticle();
        forumArticle.setTopType(topType);
        forumArticleService.updateForumArticleByArticleId(forumArticle,articleIds);
        return getSuccessResponseVO(null);
    }

    @RequestMapping("/auditArticle")
    public ResponseVO auditArticle(@VerifyParam(required = true) String articleIds) {
        forumArticleService.auditArticle(articleIds);
        return getSuccessResponseVO(null);
    }

    @RequestMapping("/loadComment")
    public ResponseVO loadComment(ForumCommentQuery commentQuery) {
        commentQuery.setLoadChildren(true);
        commentQuery.setOrderBy("post_time desc");
        return getSuccessResponseVO(forumCommentService.findListByPage(commentQuery));
    }

    @RequestMapping("/loadComment4Article")
    public ResponseVO loadComment4Article(ForumCommentQuery commentQuery) {
        commentQuery.setLoadChildren(true);
        commentQuery.setOrderBy("post_time desc");
        commentQuery.setpCommentId(0);
        return getSuccessResponseVO(forumCommentService.findListByParam(commentQuery));
    }

    @RequestMapping("/delComment")
    public ResponseVO delComment(@VerifyParam(required = true) String commentId) {
        forumCommentService.delComment(commentId);
        return getSuccessResponseVO(null);
    }

    @RequestMapping("/auditComment")
    public ResponseVO auditComment(@VerifyParam(required = true) String commentId) {
        forumCommentService.auditComment(commentId);
        return getSuccessResponseVO(null);
    }
}
